package com.dongbao.core.rules.java;

import com.dongbao.core.base.CodeRulesCommonBase;
import com.dongbao.core.rules.CodeRulesBase;
import com.dongbao.entity.AwardedInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PsiClassImpl;
import com.intellij.psi.impl.source.tree.PsiCommentImpl;
import com.intellij.psi.impl.source.tree.java.PsiExpressionStatementImpl;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.tree.IElementType;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  遵循单一职责（一个方法只做一件事)，封装数据返回结果情况可不抽
 * */
public class DuplicatedCodeRules extends CodeRulesCommonBase implements CodeRulesBase {

    public DuplicatedCodeRules(VirtualFile afterFile, PsiFile psiFile, Project project) {
        super(afterFile,psiFile,project);
        this.code = "B001";
        this.level = "B";
    }

    /**
     * 执行规则判断
     * */
    @Override
    public void run(List<AwardedInfo> deduction) {
        ApplicationManager.getApplication().invokeLater(() -> {
            /* 执行分析当前class是否负责当前规则 */
            PsiAnnotation[] annotations = psiClassImpls.get(0).getModifierList().getAnnotations();
            for(PsiClassImpl psiClass:psiClassImpls){
                /* 获取所有方法 */
                List<PsiMethod> ownMethods = psiClass.getOwnMethods();
                for(PsiMethod method:ownMethods){
                    /* 判断方法的行数是否超过了50行 超过50行则提示未进行单一原则进行编写代码 */
                    if(method.getBody().getChildren().length>50){
                        /* 获取错误代码行位置 */
                        Document document = PsiDocumentManager.getInstance(psiClass.getProject()).getDocument(psiClass.getContainingFile());
                        int lineNumber = document.getLineNumber(method.getTextOffset());
                        packDeduction(
                                deduction,
                                psiClass.getName(),
                                psiPackageStatements.get(0).getPackageName(),
                                method.getName(),
                                String.format("方法中的代码超过50行,请检查是否遵循单一原则(一个方法制作一件事)"),lineNumber,lineNumber);
                    }
                    /* todo:后面再优化是否有更好的办法判断单一原则 */
                    /* ...... */

                }
            }
        });
    }

    @Override
    public String describe() {
        return "代码结构";
    }
}
